package com.ybwh.springboot2.common.meta;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.ybwh.springboot2.common.annotation.CurrUserId;
import com.ybwh.springboot2.util.SatokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * controller方法参数解析器
 * </p>
 *
 * @author ybwh
 * @since 2019年5月17日 下午2:30:09
 */
@Slf4j
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (UserInfo.class.equals(parameter.getParameterType())) {
            return true;
        }

        if (null != parameter.getParameterAnnotation(CurrUserId.class)) {
            return true;
        }

        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();

        String token = StpUtil.getTokenValue();
        SaSession session = StpUtil.getTokenSessionByToken(token);

        if (null != parameter.getParameterAnnotation(CurrUserId.class)) {

            return Long.parseLong(SatokenUtils.getUserId());


        } else if (UserInfo.class.equals(parameter.getParameterType())) {
            return SatokenUtils.getUserInfo();
        } else {
            log.error("supportsParameter error!");
        }

        return null;

    }

}
